/********************************************************************
 * PROJECT: CSAIR ROST PROJECT.
 * SUPPLIER: FOREVER OPEN SOURCE SOFTWARE INC.
 ********************************************************************
 * FILE: ColorCache.java
 * (C) Copyright Foliage Team 2013, All Rights Reserved.
 ********************************************************************/
package org.foliage.rcp.ui.graphics;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Display;

@SuppressWarnings({ "rawtypes", "unchecked" })
public class ImageCache {

	// ----------------------------------------------- 

	private static Map mImageMap = new HashMap();

	// ----------------------------------------------- 

	public static Image getImage(final String fileName) {
		Image image = (Image) mImageMap.get(fileName);
		if (image == null) {
			image = createImage(fileName);
			mImageMap.put(fileName, image);
		}
		return image;
	}

	private static Image createImage(final String fileName) {
		final ClassLoader classLoader = ImageCache.class.getClassLoader();
		InputStream stream = classLoader.getResourceAsStream(fileName);
		if (stream == null) {
			stream = classLoader.getResourceAsStream(fileName.substring(1));

			if (stream == null) {
				stream = classLoader.getResourceAsStream(fileName);
				if (stream == null) {
					stream = classLoader.getResourceAsStream(fileName.substring(1));
					if (stream == null) {
						return null;
					}
				}
			}
		}

		final Image img = new Image(Display.getDefault(), stream);
		try {
			stream.close();
		} catch (IOException e) {
			e.printStackTrace();
		}

		return img;
	}

	// ----------------------------------------------- 

	public static void dispose() {
		final Iterator iterator = mImageMap.values().iterator();
		while (iterator.hasNext()) {
			((Image) iterator.next()).dispose();
		}
	}

}
